package com.alibaba.travel.thirdpart.controller;

import com.alibaba.travel.common.constant.LikesConstant;
import com.alibaba.travel.common.utils.R;
import com.alibaba.travel.common.utils.RRException;
import com.alibaba.travel.thirdpart.dto.LikesDto;
import com.alibaba.travel.thirdpart.interceptor.LoginInterceptor;
import com.alibaba.travel.thirdpart.scheduled.LikesRefreshScheduled;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/03/01/16:03
 * @Description:
 */
@Api(tags = {"操作redis修改点赞信息"})
@RestController
@RequestMapping("/like/likerediscontroller")
public class LikeRedisController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "点赞 / 取消", notes = "")
    @PostMapping("/click/{status}")
    public R click(@PathVariable Long status, LikesDto likesDto) {
        if (ObjectUtils.isEmpty(LoginInterceptor.userIdLocal.get())) {
            throw new RRException("用户未登录");
        }
        String key = LikesConstant.getKey(likesDto.getTopicType(),
                likesDto.getTopicId(),
                LoginInterceptor.userIdLocal.get());
        LoginInterceptor.userIdLocal.remove();
        Set<String> members = redisTemplate.opsForSet().members(key);
        if (members.size() == 0) {
            // 判断数据库状态？ 因为已经再一开始获取了数据库状态， 所以前端传播什么我们就接收什么状态
            // 直接更新状态
            redisTemplate.opsForSet().add(key, status.toString());
        } else {
            // 取出redis中的当前状态
            Integer value = Integer.parseInt(String.valueOf(members.toArray()[0]));
            if (((value + 1) % 2) == Integer.parseInt(status.toString())) {
                redisTemplate.opsForSet().pop(key);
                redisTemplate.opsForSet().add(key, String.valueOf((value + 1) % 2));
            }
        }

        return R.ok();
    }



}
